@file:Suppress("unused")

package com.hjh.tool.util

import android.content.ContentValues
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.StringRes
import androidx.core.content.edit
import androidx.core.net.toUri
import kotlin.apply
import kotlin.io.use

/**
 * @author： hjh
 * @createDate： 2025/1/2 9:46
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object SharedPreferencesHelper {

    private var authority: String = ""
    private var prefsPath: String = ""
    private var prefName: String = ""

    private val contentUri: String
        get() = "content://$authority/$prefsPath"

    /**
     * 初始化 SharedPreferences 配置
     *
     * @param authority ContentProvider 的 authority，例如 "com.zistone.app_common_server"
     * @param prefsPath 路径，例如 "prefs"
     * @param prefName SharedPreferences 文件名，例如 "com.zistone.zm805_preferences"
     */
    fun init(authority: String, prefsPath: String, prefName: String) {
        this.authority = authority
        this.prefsPath = prefsPath
        this.prefName = prefName
    }

    /**
     * 初始化 SharedPreferences 配置
     *
     * @param context Context 对象，获取包名来命名
     */
    fun init(context: Context) {
        this.authority = context.applicationContext.packageName
        this.prefsPath = "prefs"
        this.prefName = "${context.applicationContext.packageName}_preferences"
    }

    // 获取 SharedPreferences 实例
    private fun getPreferences(context: Context): SharedPreferences {
        check(prefName.isNotBlank()) { "SharedPreferencesHelper 未初始化，请先调用 init()" }
        return context.getSharedPreferences(prefName, Context.MODE_PRIVATE)
    }

    // region ---------- 通用 put/get 方法 ----------

    fun putString(context: Context, key: String, value: String) {
        getPreferences(context).edit {
            putString(key, value)
        }
    }

    fun getString(context: Context, key: String, defaultValue: String? = null): String? {
        return getPreferences(context).getString(key, defaultValue)
    }

    fun putInt(context: Context, key: String, value: Int) {
        getPreferences(context).edit {
            putInt(key, value)
        }
    }

    fun getInt(context: Context, key: String, defaultValue: Int = -1): Int {
        return getPreferences(context).getInt(key, defaultValue)
    }

    fun putBoolean(context: Context, key: String, value: Boolean) {
        getPreferences(context).edit {
            putBoolean(key, value)
        }
    }

    fun getBoolean(context: Context, key: String, defaultValue: Boolean = false): Boolean {
        return getPreferences(context).getBoolean(key, defaultValue)
    }

    fun putLong(context: Context, key: String, value: Long) {
        getPreferences(context).edit {
            putLong(key, value)
        }
    }

    fun getLong(context: Context, key: String, defaultValue: Long = -1L): Long {
        return getPreferences(context).getLong(key, defaultValue)
    }

    fun putFloat(context: Context, key: String, value: Float) {
        getPreferences(context).edit {
            putFloat(key, value)
        }
    }

    fun getFloat(context: Context, key: String, defaultValue: Float = -1f): Float {
        return getPreferences(context).getFloat(key, defaultValue)
    }

    fun remove(context: Context, key: String) {
        getPreferences(context).edit {
            remove(key)
        }
    }

    fun clear(context: Context) {
        getPreferences(context).edit {
            clear()
        }
    }

    fun all(context: Context): MutableMap<String, *>? {
        return getPreferences(context).all
    }

    // endregion

    // region ---------- 通过 URI 操作 ----------

    private fun putStringByURI(context: Context, key: String, value: String): Boolean {
        val uri = "$contentUri/$key".toUri()
        val contentValues = ContentValues().apply {
            put("value", value)
        }
        val rowsUpdated = context.contentResolver.update(uri, contentValues, null, null)
        return rowsUpdated > 0
    }

    fun getStringByURI(context: Context, key: String, defaultValue: String? = null): String? {
        val uri = "$contentUri/$key".toUri()
        val cursor = context.contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                return it.getString(it.getColumnIndexOrThrow("value"))
                    ?: getString(context, key, defaultValue)
            }
        }
        return getString(context, key, defaultValue)
    }

    // 同时通过常规和 URI 保存字符串
    fun saveString(context: Context, @StringRes keyRes: Int, value: String) {
        val key = context.getString(keyRes)
        putString(context, key, value)
        putStringByURI(context, key, value)
    }

    // endregion
}

